package com.example.demo.control;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 图表
 */
@Controller
public class ChartControl {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 跳转到图表页面
     * @return
     */
    @RequestMapping("/chart")
    public String chart() {
        return "chart";
    }

    /**
     * 获取图表数据——销售数据
     * @return 日期、订单金额、支付金额
     */
    @RequestMapping("/sales")
    @ResponseBody
    public Map<String, List> getChartData() {
        List<String> dates = new ArrayList<>();//日期
        List<Double> orderAmounts = new ArrayList<>();//订单金额
        List<Double> payAmounts = new ArrayList<>();//支付金额

        //绘图时数据从左到右,日期小的在前
        //获取最近7天的日期，从今天开始往前推6天
        for (int i = -6; i<=0; i++) {
            String date=LocalDate.now().plusDays(i).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            dates.add(date);

            Double orderAmount = (Double)redisTemplate.opsForValue().get("order-"+date);
            if (orderAmount == null) {
                orderAmount = 0d;
            }
            orderAmounts.add(orderAmount);

            Double payAmount = (Double)redisTemplate.opsForValue().get("payment-"+date);
            if (payAmount == null) {
                payAmount = 0d;
            }
            payAmounts.add(payAmount);
        }

        Map<String, List> result = new HashMap();
        result.put("dates", dates);
        result.put("orderAmounts", orderAmounts);
        result.put("payAmounts", payAmounts);
        return result;
    }

}
